//项目名称
var basePath = $("#basePath").attr("href");
//语音基本信息相关
var base = {
    callDirectionArr: [],//用来存储呼叫类型状态
    onHookArr: [],//用来存储挂机方状态
    reCallFlagArr: [],//用来存储重复来电状态
    agreeArr: [],//用来存储满意度状态
    customerLevelArr:[],//用来存储客户星级
    customerlocArr:[],//用来存储地市信息
    proArr:[],//用来存储省份信息
    init: function () {
        base.selectProvince();
        base.getBase();
        base.tabLegend();
        $("#baseChange").on("click",function(){
            var box=$(".baseBox");
            var ul=box.find("ul");
            var length=ul.length;
            var height=35;
            if(box.height()!=(height*2-10)){
                box.animate({"height":(height*2-10)+"px"},500);
                $(this).html('展开<b class="fa fa-angle-double-down"></b>');
            }else{
                box.animate({"height":(height*length-10)+"px"},500);
                $(this).html('收起<b class="fa fa-angle-double-up"></b>');
            }
        });
        base.onHookArr= bs.getStatus("audio_onhook");
        base.reCallFlagArr= bs.getStatus("recall_flag");
        base.agreeArr= bs.getStatus("audio_satisfaction");
        base.callDirectionArr= bs.getStatus("call_direction");
        base.customerLevelArr= bs.getStatus("audio_customer_level");
    },
    getBase: function () {
        $.ajax({
            type: "post",
            url: basePath + "/rest/pending-task-detail/get-audio-mgs",
            dataType: "json",
            data: {
                serialNumber: $("#serialNumber").html()
            },
            success: function (data) {
                if (data.code == 0) {
                    $.ajax({
                        type: "POST",
                        url: basePath + 'rest/common/getProvinceCity',
                        dataType: "json",
                        contentType: 'application/json',
                        data: JSON.stringify({"provinceCode":data.data.provinceCode}),
                        async: false,
                        success: function (data) {
                            var result = data.data;
                            base.customerlocArr=result;
                        }
                    });
                    base.renderBase(data.data)
                } else {
                    toastrCog.error(data.msg, 3000)
                }
            }
        })
    },
    renderBase: function (data) {
        var msg = data;
        $("#seatGroup").html(msg.seatGroup);
        $("#seatWorker").html(msg.seatId);
        $("#seatName").html(msg.seatName);
        $("#callType").html(bs.changeState(msg.callDirection,base.callDirectionArr));
        $("#phone").html(msg.customerNum);
        $("#audioId").html($("#serialNumber").html()).attr("data-id",bs.getXInY(base.proArr,"id","value",msg.provinceCode));
        $("#phoneStartTime").html(msg.callStartTime);
        $("#phoneEndTime").html(msg.callEndTime);
        $("#timeDur").html("<b>" + base.formatSeconds(msg.holdDuration) + "</b>");
        $("#satisfaction").html(bs.changeState(msg.satisfaction,base.agreeArr));
        $("#onHook").html(bs.changeState(msg.onHook,base.onHookArr));
        $("#reCallFlag").html(bs.changeState(msg.reCallFlag,base.reCallFlagArr));
        $("#customerLevel").html(bs.changeState(msg.customerLevel,base.customerLevelArr,"1"));
        $("#proPhoneNum").html(msg.proPhoneNum);
        var customerloc=base.customerlocArr[msg.customerloc];
        if(!customerloc){
            customerloc=msg.customerloc;
        }
        $("#customerloc").html(customerloc);
        $(".baseBox span").each(function(){
            $(this).attr("title",$(this).text())
        })
    },
    selectProvince: function () {
        base.proArr = bs.getProvince();
    },
    tabLegend: function () {
        $("legend").on("click", function () {
            if ($(this).hasClass("on")) {
                $(this).next(".fieldset_box").slideUp(300,function(){
                    resize.me();
                });
                $(this).removeClass("on");
                $(this).find(".fa").removeClass("fa-angle-up").addClass("fa-angle-down");
            } else {
                $(this).next(".fieldset_box").slideDown(300,function(){
                    resize.me();
                });
                $(this).addClass("on");
                $(this).find(".fa").removeClass("fa-angle-down").addClass("fa-angle-up");
            }
        })
    },
    formatSeconds: function (value) {
        var secondTime = parseFloat(value);// 秒
        var minuteTime = 0;// 分
        var hourTime = 0;// 小时
        if (secondTime > 60) {//如果秒数大于60，将秒数转换成整数
            //获取分钟，除以60取整数，得到整数分钟
            minuteTime = parseFloat(secondTime / 60);
            //获取秒数，秒数取佘，得到整数秒数
            secondTime = parseFloat(secondTime % 60);
            //如果分钟大于60，将分钟转换成小时
            if (minuteTime > 60) {
                //获取小时，获取分钟除以60，得到整数小时
                hourTime = parseFloat(minuteTime / 60);
                //获取小时后取佘的分，获取分钟除以60取佘的分
                minuteTime = parseFloat(minuteTime % 60);
            }
        }
        var result = "" + parseFloat(secondTime).toFixed(2) + "";

        if (minuteTime > 0 && secondTime < 10) {
            result = "0" + parseFloat(secondTime).toFixed(2) + "";
        }

        if (minuteTime > 0) {
            result = "" + parseInt(minuteTime) + ":" + result;
        }
        if (hourTime > 0) {
            result = "" + parseInt(hourTime) + ":" + result;
        }
        return result;
    },
    isNull: function (value) {
        if (!value) {
            value = ""
        }
        return value;
    }
};
//波形相关
var wave = {
    skipLength: 5,
    wavesurfer: null,
    audioLength: 0,
    scrolFlg: 0,//A路语音当前的滚动标记，=10时，滚动一次stt
    sttsF: 3,//多少次触发一次stt关键词滚动事件
    speedArr: [0.5, 1.0, 1.5, 2.0],
    init: function () {
        wave.initWave();
        wave.changeSpeed();
        wave.jumpSecound();
        wave.isExist();
        var speedArrOption = [];
        var obj;
        for(var i=0;i<wave.speedArr.length;i++){
            obj = {};
            obj.name = wave.speedArr[i];
            obj.value = wave.speedArr[i];
            speedArrOption.push(obj);
        }
        bs.selectDown($("#audioSpeed"), speedArrOption, 1,'60px');
        $("#audioSpeed").val('1').trigger("chosen:updated");
        wave.wavesurfer.un('audioprocess');
        wave.wavesurfer.on('audioprocess', wave.onAudioProgress);
        wave.wavesurfer.on('seek', function () {
            $("#nowTime").html(base.formatSeconds(parseInt(wave.wavesurfer.getCurrentTime())));
        });
        $(".wave").on("mousewheel", function (e, delta) {
            if (delta > 0) {
                wave.zoomAudioIn();
            } else if (delta < 0) {
                wave.zoomAudioOut();
            }
            return false;
        });
        $("#playStopTab").on("click", function () {
            wave.changePlayStop();
        })
        // wave.initKey();
    },
    changePlayStop: function () {
        if (wave.wavesurfer.isPlaying()) {
            $("#playStopTab").html('<span class="glyphicon glyphicon-pause"></span>');
        } else {
            $("#playStopTab").html('<span class="glyphicon glyphicon-play"></span>');
        }
    },
    initWave: function () {
        wave.wavesurfer = WaveSurfer.create({
            container: '.speakerModel-player',
            waveColor: '#ddd',
            progressColor: '#54f176',
            height: 110,
            skipLength: wave.skipLength,
            maxCanvasWidth:32760,
            renderer:'MultiCanvas'
        });
        wave.wavesurfer.on('ready', function () {
            $("#sp-player-wrapper").hide();
            var timeline = Object.create(WaveSurfer.Timeline);
            timeline.init({
                wavesurfer: wave.wavesurfer,
                container: '.waveTime_one',
//                    primaryFontColor: "#fff",
//                    secondaryFontColor: "#fff",
//                    primaryColor: "#fff",
            });
            wave.audioLength = wave.wavesurfer.getDuration();
            $("#totalTime").html(base.formatSeconds(parseInt(wave.audioLength)));
            var minPP = Number($(".wave").width() - 30) / wave.audioLength;
            wave.wavesurfer.zoom(minPP);
            var maxPP = minPP * 100;//最大100倍，越大越耗内存
            $("#myPlayer-room-input").attr({"max": maxPP, "min": minPP});
            $("#myPlayer-room-input").val(minPP);
            $(".waveInput").prop("disabled",false);
        });
        wave.wavesurfer.on('loading', function (percent) {
            $("#sp-player-loadBar").width(percent + "%");
            if (percent >= 100) {
                $("#sp-player-loadBar").html("加载波形中...");
            } else {
                $("#sp-player-loadBar").html(percent + "%");
            }
        });
        wave.wavesurfer.on('error', function () {
            $("#sp-player-loadBar").width("100%");
            $("#sp-player-loadBar").html("语音加载错误...");
        });
        wave.wavesurfer.on('play',function () {
            $("#playStopTab").find("span").attr("class","glyphicon glyphicon-pause");
        });
        wave.wavesurfer.on('pause',function () {
            $("#playStopTab").find("span").attr("class","glyphicon glyphicon-play");
        })
    },
    playPause: function () {
        try {
            wave.clearRegions();
            wave.wavesurfer.playPause();
        } catch (e) {

        }

    },
    stop: function () {
        if (wave.wavesurfer.isPlaying()) {
            wave.wavesurfer.stop();
        }
    },
    skipBackward: function (step) {
        wave.wavesurfer.skipBackward(step);

    },
    skipForward: function (step) {
        wave.wavesurfer.skipForward(step);
    },
    initKey: function () {
        $('body').bind("keydown", function (e) {
            try {//兼容浏览器取键值
                e = e || event;
                var k = e.keyCode || e.which || e.charCode;
                if (k == 9) {//播放/暂停
                    wave.playPause();
                } else if (k == 70) {//停止
                    wave.stop();
                } else if (k == 39) {//上一句
                    wave.skipForward(wave.skipLength);
                } else if (k == 37) {//下一句
                    wave.skipBackward(wave.skipLength);
                }

                e.preventDefault();  // 阻止默认行为
                e.stopPropagation();
            } catch (e) {

            }
            return true;
        });
    },
    jumpSecound: function () {
        // $(".waveInput").on("keyup", function (e) {
        //     var code = e.charCode || e.keyCode;
        //     if (code == 13) {
        //         wave.jump();
        //     }
        // });
        // $(".waveInput").on("blur", function (e) {
        //     wave.jump();
        // });
        $("#jumpBtn").on("click", function () {
            wave.jump();
        })

    },
    jump: function () {
        var hour = parseInt($(".waveInput.hour").val());
        var minute = parseInt($(".waveInput.minute").val());
        var seconds = parseInt($(".waveInput.seconds").val());
        hour = isNaN(hour) ? 0: hour;
        minute = isNaN(minute) ? 0: minute;
        seconds = isNaN(seconds) ? 0: seconds;
        var value = hour*60*60 + minute*60 + seconds;
        var reg = /^[0-9]+$/;
        var reg60 =/^([0-9]|[1-5]\d|60)$/;
        var valide = true;
        var num = 0;
        $(".waveInput").each(function(){
            if($(this).val()!=''){
                if ($(this).val().indexOf(" ")>-1) {
                    valide = false;
                    toastrCog.error("不能输入空格！", 2000);
                    return
                }
                if($(this).hasClass('hour')){
                    if (!reg.test($(this).val())) {
                        valide = false;
                        toastrCog.error("请输入大于等于0的整数！", 2000);
                        return
                    }
                }else{
                    if (!reg60.test($(this).val())) {
                        valide = false;
                        toastrCog.error("请输入大于等于0小于等于60的整数！", 2000);
                        return
                    }
                }
            }else{
                num++;
            }
        });
        if(num == 3){
            toastrCog.error("时分秒不能为空！", 2000);
            return
        }
        if(!isNaN(value)){
            if(valide){
                if (value>wave.audioLength) {
                    toastrCog.error("不能超过语音时长！", 2000);
                    return
                }
                wave.wavesurfer.play(value);
            }
        }
    },
    onAudioProgress: function (time) {
        $("#nowTime").html(base.formatSeconds(parseInt(time)));
        //平均大概0.03s触发一次该事件，
        // 为了提高网页效率，该事件每触发10次，即平均每0.3s滚动一次stt和关键词
        wave.scrolFlg++;
        if (wave.scrolFlg % wave.sttsF == 0) {
            stt.scrollToStt(time);
        }
        // 为了提高网页效率，该事件每触发10次，即平均每0.3s滚动一次stt
        if (wave.scrolFlg == 100) {
            wave.scrolFlg = 0;//避免flag过大
        }
    },
    playRegion: function (startTime, endTime) {
        startTime = Number(startTime);
        endTime = Number(endTime);
        wave.clearRegions();
        if (startTime != null && endTime != null) {
            var aTime = wave.wavesurfer.getCurrentTime();
            if (aTime > wave.audioLength)
                return;
            var id = new Date().getTime();
            wave.addRegion(id, startTime, endTime);
            wave.wavesurfer.play(startTime, endTime);
        }
    },
    addRegion: function (id, startTime, endTime) {
        var waves = wave.wavesurfer;
        startTime = wave.toDecimal1(startTime, 2);
        endTime = wave.toDecimal1(endTime, 2);
        if (startTime != null && endTime != null) {
            waves.addRegion({
                id: id,
                start: startTime,
                end: endTime,
                color: "rgba(101, 183, 228, 0.56)",
                drag: false,
                resize: false
            });
        }
    },
    clearRegions: function (elem) {
        var waves = wave.wavesurfer;
        if (waves.regions && waves.regions.list) {
            waves.clearRegions();//清空片段
        }
    },
    toDecimal1: function (x) {//功能：将浮点数四舍五入，取小数点后1位
        var f = parseFloat(x);
        if (isNaN(f)) {
            return;
        }
        f = Math.round(x * 10) / 10;
        return f;
    },
    changeSpeed: function () {
        $("#audioSpeed").on('change', function (e, params) {
            var val = params.selected;
            wave.wavesurfer.setPlaybackRate(val);
        });
    },
    zoomAudioIn: function () {
        var roomInput = $("#myPlayer-room-input");
        var v = Number(roomInput.val());
        var minV = Number(roomInput.attr("min"));
        var maxV = Number(roomInput.attr("max"));
        if (v != maxV) {
            //var showNum=Number($("#myPlayer-room").text());
            var num = minV * 0.5;
            num = num < 1 ? 1 : num;
            if (v < maxV - num) {
                v = v + num;
                //    showNum=showNum+0.5;
            } else if (v < maxV) {
                v = maxV;
                //    showNum=maxV/minV;
            } else {
                return;//不再变化
            }
            //$("#myPlayer-room").text(showNum.toFixed(1));
            roomInput.val(v);
            wave.wavesurfer.zoom(v);
        }
    },
    zoomAudioOut: function () {
        var roomInput = $("#myPlayer-room-input");
        var v = Number(roomInput.val());
        var minV = Number(roomInput.attr("min"));
        if (v != minV) {
            //var showNum=Number($("#myPlayer-room").text());
            var num = minV * 0.5;
            num = num < 1 ? 1 : num;
            if (v > minV + num) {
                v = v - num;
                //    showNum=showNum-0.5;
            } else if (v > minV) {
                v = minV;
                //   showNum=1;
            } else {
                return;//不再变化
            }
            //$("#myPlayer-room").text(showNum.toFixed(1));
            roomInput.val(v);
            wave.wavesurfer.zoom(v);
        }
    },
    zoomAudio: function () {
        var roomInput = $("#myPlayer-room-input");
        var minV = Number(roomInput.attr("min"));
        roomInput.val(minV);
        wave.wavesurfer.zoom(minV);
    },
    isExist: function () {
        $.ajax({
            type: "post",
            url: basePath + "/rest/pending-task-detail/is-audio-exists",
            dataType: "json",
            data: {
                serialNumber: $("#serialNumber").html()
            },
            success: function (data) {
                if (data.code == 0) {
                    var url = data.msg;
                    // needTagging.init();
                    wave.wavesurfer.load(basePath + "/rest/pending-task-detail/get-audio-io?audioUrl=" + url);
                    if ($("#userIdentity").text() !=0) {//坐席看不到按钮
                        if($("#reW").length>0){
                            $("#reW").show();
                        }
                    }
                } else {
                    toastrCog.error(data.msg, 3000);
                    $(".needTagging").css("background","rgb(235, 235, 228)").css("color","#666").css("cursor","not-allowed");
                    $(".needTagging").off("click");
                }
            }
        })
    },

};
//标签相关
var tag = {
    tagsArr: null,
    modelSelectIdArr: [],
    init: function () {
        tag.getTag();
        tag.addTag();
        tag.delTag();
        if($("#tagModal").length == 0){
            tag.appendModal($('body'));
        }
        $("#searchTagName").on("click",function(){
            if($("#tagId").val()!=""){
                $("#jstreeTag").jstree("deselect_all", true);
            }
            $("#tagId").val("");
            $("#tagTableWin").bootstrapTable('refreshOptions', {pageNumber:1});
            $("#tagTableWin").bootstrapTable('refresh');
        });
        $("#searchTagName").prev().on("keyup", function (e) {
            var code = e.charCode || e.keyCode;
            if (code == 13) {
                //此处编写用户敲回车后的代码
                $("#searchTagName").click();
            }
        });
        //全部删除
        $("#tagModal").on("click", "#deleteAllTag", function () {
            tag.modelSelectIdArr = [];
            $('.tagSModel ul').html('');
            $('#tagTableWin').bootstrapTable("refresh");
        });
    },
    getTag: function () {
        $.ajax({
            type: "post",
            url: basePath + "/rest/pending-task-detail/get-tag-list",
            dataType: "json",
            data: {
                serialNumber: $("#serialNumber").html()
            },
            success: function (data) {
                if (data.code == 0) {
                    tag.renderTag(data.data)
                } else {
                    toastrCog.error(data.msg, 3000);
                }
            }
        })
    },
    renderTag: function (data) {
        var ul = $(".tags");
        ul.html("");
        for (var i = 0; i < data.length; i++) {
            var tagName = data[i].tagName;
            var proType = data[i].proType;
            var tagId = data[i].tagId;
            var $li = $('<li data-type="' + proType + '" data-id="' + tagId + '" class="type' + proType + '" data-name="'+tagName+'">' +
                '<span>' + tagName + '</span>' +
                '<b class="fa fa-close noPer" style="display: none" title="删除标签"></b>' +
                '</li>');
            if (proType == 0) {
                $li.find("b").remove();
            }
            $li.hover(function () {
                if($("#plusTag").length!=0){//话务小节不能删除
                    $(this).find("b").show();
                }
            }, function () {
                $(this).find("b").hide();
            });
            ul.append($li);
        }
        if ($("#userIdentity").text() ==0) {
            console.log($("#plusTag"))
            ul.find("b").remove();
            $("#plusTag").remove();
        }
    },
    addTag: function () {
        $("#plusTag").one("click", function () {
            menuTag.init();
        });
        $("#plusTag").on("click", function () {
            tag.modelSelectIdArr = []
            $("#searchMenuTag").prev().val("");
            $("#searchTagName").prev().val("");
            $("#jstreeTag").jstree("deselect_all", true);
            $("#tagId").val('')
            $("#tagName").val('')
            $(".tags li").each(function(){
                var id=$(this).attr("data-id");
                var name=$(this).attr("data-name");
                var tagtype=$(this).attr("data-type");
                var obj = {};
                obj.id = id;
                obj.name = name;
                obj.content = name;
                obj.tagtype = tagtype;
                if(obj.tagtype!=0){
                    tag.modelSelectIdArr.push(obj);
                }
            });
            var tagTable = new TableInitTag();
            tagTable.Init();
            $("#tagModal").modal("show");
        });
        $("body").on("click",'#save',function () {
            var selectArr = tag.modelSelectIdArr;
            var length = selectArr.length;
            var arr = [];
            var arrName = [];
            for (var i = 0; i < length; i++) {
                var id = selectArr[i].id;
                var content = selectArr[i].content;
                arr.push(id);
                arrName.push(content);
            }
            $.ajax({
                type: "post",
                url: basePath + "/rest/pending-task-detail/add-tag",
                dataType: "json",
                data: {
                    serialNumber: $("#serialNumber").html(),
                    tagIds: arr.join(","),
                    tagNames: arrName.join(",")
                },
                success: function (data) {
                    if (data.code == 0) {
                        tag.getTag();
                        toastrCog.success(data.msg, 1000)
                    } else {
                        toastrCog.error(data.msg, 3000)
                    }
                }
            })
            $("#tagModal").modal("hide");
        })
    },
    delTag: function () {
        $(".tags").on("click", "li b", function () {
            var type = $(this).parents("li").attr("data-type");
            var id = $(this).parents("li").attr("data-id");
            $("#tagDelModal").modal("show").attr(
                {
                    "data-name": $(this).parents("li").text(),
                    "data-type": type,
                    "data-id": id
                }
            );
            $("#delName").html($(this).parents("li").text());
        });
        $(".tagSModel").on("click", "li b", function () {
            var $li=$(this).parents("li");
            var content = $li.text();
            for(var i=0;i<tag.modelSelectIdArr.length;i++){
                var contentOld=tag.modelSelectIdArr[i].content;
                if(contentOld == content){
                    tag.modelSelectIdArr.splice(i,1)
                }
            }
            $li.remove();
            $("#tagTableWin").bootstrapTable('refresh');
        });
        $("#delBtn").on("click", function () {
            $.ajax({
                type: "post",
                url: basePath + "/rest/pending-task-detail/del-tag",
                dataType: "json",
                data: {
                    serialNumber: $("#serialNumber").html(),
                    tagName: $("#tagDelModal").attr("data-name"),
                    tagType: $("#tagDelModal").attr("data-type")
                },
                success: function (data) {
                    $("#tagDelModal").modal("hide")
                    if (data.code == 0) {
                        toastrCog.success(data.msg, 1000);
                        tag.getTag();
                    } else {
                        toastrCog.error(data.msg, 3000)
                    }
                }
            })
        });
    },
    renderSelectTag:function(){
        var ul=$(".tagSModel ul");
        ul.html("");
        for(var i=0;i<tag.modelSelectIdArr.length;i++){
            var content=tag.modelSelectIdArr[i].content;
            var tagtype=tag.modelSelectIdArr[i].tagtype;
            if(content==null){
                content=""
            }
            if(tagtype!=0){
                var $li=$('<li title="分类：'+content+'">'+content+'<b class="fa fa-close noPer" style="display: none" title="删除标签"></b></li>');
                $li.hover(function () {
                    $(this).find("b").show();
                }, function () {
                    $(this).find("b").hide();
                });
                ul.append($li);
            }
        }
    },
    appendModal:function(elem){
        var str = '<div class="modal fade" id="tagModal" tabindex="-1" role="dialog" aria-hidden="true" data-backdrop="static">' +
            '    <div class="modal-dialog" style="width: 1005px;">' +
            '        <div class="modal-content">' +
            '            <div>' +
            '                <div class="modal-header">' +
            '                    <button type="button" class="close" data-dismiss="modal"><span' +
            '                            aria-hidden="true">&times;</span><span' +
            '                            class="sr-only">Close</span></button>' +
            '                    <h4 class="modal-title">添加标签</h4>' +
            '                </div>' +
            '                <div class="modal-body">' +
            '                    <div class="selectModel" style="height:581px !important;">' +
            '                        <div class="menu_left">' +
            '                            <div class="search_box">' +
            '                                <input type="text" autocomplete="off"><span class="fa fa-search fa_btn" id="searchMenuTag"></span>' +
            '                            </div>' +
            '                            <div id="jstreeTag" class="scrollbar">' +
            '' +
            '                            </div>' +
            '                        </div>' +
            '                        <div class="model_right" style="width:480px;height: 100%;">' +
            '                            <div class="search_box">' +
            '                                <input type="text" autocomplete="off" placeholder="标签名称" style="width: 450px;" id="tagName"><span class="fa fa-search fa_btn" id="searchTagName"></span>' +
            '                            </div>' +
            '                            <table id="tagTableWin"></table>' +
            '                        </div>' +
            '                        <div class="model_right" style="width: 270px;height: 566px;">' +
            '                            <div class="tagSModel">' +
            '                                <div>已选标签：<span class="fa_btn_search deleteAllTag" id="deleteAllTag">全删</span></div>' +
            '                                <ul>' +
            '                                </ul>' +
            '                            </div>' +
            '                        </div>' +
            '                    </div>' +
            '                </div>' +
            '                <div class="modal-footer">' +
            '                    <button type="button" class="btn btn-primary" id="save">保存</button>' +
            '                    <button type="button" class="btn btn-white" data-dismiss="modal">关闭</button>' +
            '                </div>' +
            '            </div>' +
            '        </div>' +
            '    </div>' +
            '</div>';
        elem.append(str);
    }
};
var menuTag = {
    init: function () {
        menuTag.render();
        menuTag.changeMenu();
        menuTag.search();
    },
    render: function (node) {
        var jstree = $("#jstreeTag");
        $('#jstreeTag').jstree("destroy");
        $('#jstreeTag').data('jstree', false).empty();
        jstree.jstree({
            "core": {
                "animation": false,
                "multiple": false,
                "check_callback": true,
                'data': function (obj, callback) {
                    $.ajax({
                        type: "GET",
                        url: basePath + 'rest/busTag/showTagTree',
//                            async: false,
                        data:{
                            "tagType":1,
                            "areaId": $("#audioId").attr("data-id")
                        },
                        success: function (result) {
                            callback.call(this, menuTag.loopMenu(result.children));
                        }
                    });
                }
            },
            "types": {
                "default": {
                    "icon": "jstree-folder"
                },
                "html": {
                    "icon": "jstree-file"
                }
            },
            "plugins": ["types", "search", "unique", "contextmenu", "changed"]
        }).bind('loaded.jstree', function (e, data) {
            jstree.jstree("deselect_all", true);
            var obj = jstree.jstree("get_node", node);
            jstree.jstree('select_node', obj, true);
            $("li[aria-selected='true']").click();
        });
    },
    getNoteInID: function (id) {
        var str = "";
        $.ajax({
            type: "post",
            url: basePath + 'rest/busTag/getTagByPK',
            async: false,
            data: {
                id: id
            },
            success: function (result) {
                if (result != null) {
                    str = result.note
                }
            }
        });
        return str;
    },
    loopMenu: function (array) {
        if (array.length > 0) {
            for (var i = 0; i < array.length; i++) {
                var children = array[i]["children"];
                if (children.length <= 0) {
                    array[i].type = "html"
                } else {
//                        if(i<=1){
//                        array[i].state = {"opened": "true"}
//                        }
                }
                array[i].state = {"opened": false};
                if (children) {
                    menuTag.loopMenu(children);
                }
            }
            return array;
        }
    },
    changeMenu: function () {
        $('#jstreeTag').on("changed.jstree", function (e, data) {
            // 当选中某个节点时 表格重新加载
            var selectNode = $("#jstreeTag").jstree("get_node", data.selected);
            if (data.selected.length > 0) {
                if (data.selected > 0) {  //如果选中的节点不是省份信息
                    // 选中的是标签节点 把选中的节点值放到tagId中
                    $("#areaId").val(selectNode.original.areaId);
                    $("#tagId").val(selectNode.original.tagId);
                    $("#tagType").val(selectNode.original.tagType);
                } else {
                    // 判断节点level 从而判断是选中的省份节点还是标签标识节点
                    var level = selectNode.original.level;
                    if(level == 2){
                        // 选中的是标识节点 获取省份id 清空tagId
                        $("#areaId").val(selectNode.original.areaId);
                        $("#tagId").val("");
                        $("#tagType").val(selectNode.original.tagType);
                    }else {
                        // 选中的是省份节点 获取省份id 清空标识tagType和tagId
                        $("#areaId").val(selectNode.original.areaId);
                        $("#tagId").val("");
                        $("#tagType").val("");
                    }
                }
                $("#tagTableWin").bootstrapTable('refreshOptions', {pageNumber:1});
                $("#tagTableWin").bootstrapTable("refresh");
            }

        });
    },
    search: function () {
        $("#searchMenuTag").on("click", function () {
            $("#jstreeTag").jstree(true).search($.trim($(this).prev().val()));
            menuTag.scrollSearch($("#jstreeTag"));
        });
        $("#searchMenuTag").prev().on("keyup", function (e) {
            var code = e.charCode || e.keyCode;
            if (code == 13) {
                $("#jstreeTag").jstree(true).search($.trim($(this).val()));
                menuTag.scrollSearch($("#jstreeTag"));
            }
        })
    },
    scrollSearch: function (elem) {
        if (elem.find(".jstree-search").length > 0) {
            var odiv = elem.find(".jstree-search").eq(0)[0];
            var top = odiv.offsetTop;
            var height = odiv.offsetHeight;
            var elemTop = elem[0].scrollTop;
            //获取当前屏幕大小
            var size = elem.height();
            //加上元素本身的高度，是元素全部出现事件
            if ((top + height) < (elemTop + size) && (top + height) > elemTop) {

            } else {
                elem.animate({scrollTop: top - 70}, "slow");
            }
        }
    },
    getMenuData: function () {
        var arr = [];
        $.ajax({
            type: "GET",
            url: basePath + 'rest/busTag/showTagTree',
//                async: false,
            success: function (result) {
                if (result != null) {
                    arr.push(result);
                }
            }
        });
        return arr;
    },
    refresh: function () {
        var tree = $('#jstreeTag');
        tree.jstree(true).settings.core.data = menuTag.loopMenu(menuTag.getMenuData()); // 新数据
        tree.jstree(true).refresh(); //刷新树
    }
};
var TableInitTag = function () {
    var oTableInit = new Object();
    var url = basePath + "/rest/busTag/busLeafTagByPage";
    //初始化Table
    oTableInit.Init = function () {
        $('#tagTableWin').bootstrapTable("destroy");
        $('#tagTableWin').bootstrapTable({
            url: url,         //请求后台的URL（*）
            method: "post", //请求方式（*）
            dataType: "json",
            contentType: "application/x-www-form-urlencoded;charset=UTF-8",
            dataField: "rows", //服务端返回数据键值 就是说记录放的键值是rows，分页时使用总记录数的键值为total
            totalField: "total",
            striped: true, //是否显示行间隔色
            cache: false, //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            pagination: true, //是否显示分页（*）
            sortable: false, //是否启用排序
            sortName: "id", //排序方式
            sortOrder: "asc", //排序方式
            clickToSelect: true,
            queryParams: oTableInit.queryParams, //传递参数（*）
            queryParamsType: "", //  queryParamsType = 'limit' 参数: limit, offset, search, sort, order;
            sidePagination: "server", //分页方式：client客户端分页，server服务端分页（*）
            pageNumber: 1, //初始化加载第一页，默认第一页
            pageSize: 10, //每页的记录行数（*）
            pageList: [10, 15, 20, 25], //可供选择的每页的行数（*）
            idField: "id",
            uniqueId: "id", //每一行的唯一标识，一般为主键列
            responseHandler: function (res) {
                var selectArr = tag.modelSelectIdArr;
                var arr = res.result;
                if (selectArr.length > 0 && arr.length > 0) {
                    for (var i = 0; i < arr.length; i++) {
                        for (var j = 0; j < selectArr.length; j++) {
                            if (selectArr[j]["content"] == arr[i]["content"]) {
                                arr[i]["state"] = true;
                            }
                        }
                    }
                }
                return {
                    "total": res.totalCount,//总页数
                    "rows": arr   //数据
                };
            },
            columns: [
                {
                    checkbox: true, // 显示一个勾选框
                    align: 'center', // 居中显示
                    formatter: function (value, row, index) {
                        if (row.state == true)
                            return {
                                disabled: false,//设置是否可用
                                checked: true//设置选中
                            };
                        return value;
                    }
                },
                {
                    align: "center",
                    halign: "center",
                    title: '序号',//标题  可不加
                    width: 60,
                    field: 'id',
                    sortable: true,
                    formatter: function (value, row, index) {
                        var getOptions = $("#tagTableWin").bootstrapTable('getOptions');
                        var pagenum = getOptions.pageNumber;
                        var pagesize = getOptions.pageSize;
                        var st = (pagenum - 1) * pagesize;
                        return (st + index + 1) + "";
                    }
                },
                {
                    align: "center",
                    halign: "center",
                    field: 'provincename',
                    title: '省份',
                    sortable: true
                },
                {
                    align: "center",
                    halign: "center",
                    field: 'content',
                    title: '标签分类',
                    sortable: true
                }, {
                    align: "center",
                    halign: "center",
                    field: 'name',
                    title: '标签名称',
                    sortable: true
                },
//                    {
//                        align: "left",
//                        halign: "center",
//                        field: 'content',
//                        title: '内容',
//                        sortable: true
//                    },
//                    {
//                        align: "center",
//                        halign: "center",
//                        field: 'note',
//                        title: '备注',
//                        sortable: true
//                    }
//                    , {
//                        align: "center",
//                        halign: "center",
//                        field: 'createusername',
//                        title: '创建人',
//                        sortable: true
//                    }, {
//                        align: "center",
//                        halign: "center",
//                        field: 'createtime',
//                        title: '创建时间',
//                        sortable: true,
//                        formatter: function (value, row, index) {
//                            return dateFormatUtil(value)
//                        }
//                    }
            ],
            onLoadSuccess: function (data) {  //加载成功时执行
                $("#tagTableWin").find("input[name='btSelectAll']").hide();
                tag.renderSelectTag();
                if (!data.total || data.total == 0) {
                    $(".no-records-found").find("td").html('<img src="../../../assert/image/nodata.png" th:src="@{/assert/image/nodata.png}" style="width:165px;" alt="">');
                }
            },
            onLoadError: function () {  //加载失败时执行
//                    toastr.error('加载数据失败！');
                $(".no-records-found").find("td").html('<img src="../../../assert/image/nodata.png" th:src="@{/assert/image/nodata.png}" style="width:165px;" alt="">');
            },
            onCheck: function (row, tr) {
                tag.modelSelectIdArr.push(row);
                tag.renderSelectTag();
            },
            onUncheck: function (row, tr) {
                var content = row.content;
                for (var i = 0; i < tag.modelSelectIdArr.length; i++) {
                    if (tag.modelSelectIdArr[i].content == content) {
                        tag.modelSelectIdArr.splice(i, 1)
                    }
                }
                tag.renderSelectTag();
            },
            onResetView: function (data) {
                $("#tagModal .fixed-table-body").css("maxHeight",430+"px");
            },
            formatLoadingMessage: function () {
                return '<div class="loaded">' +
                    '<div class="loader">' +
                    '<div class="loader-inner line-scale-pulse-out">' +
                    '<div></div>' +
                    '<div></div>' +
                    '<div></div>' +
                    '<div></div>' +
                    '<div></div>' +
                    '</div>' +
                    '</div>' +
                    '</div>' +
                    '<div>请稍等，数据正在加载中...</div>';
            }
        });
    };
    //得到查询的参数
    oTableInit.queryParams = function (params) {
        var temp = { //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
            "pageSize": params.pageSize,
            "pageNum": params.pageNumber,
            "sortName": this.sortName,
            "sortOrder": this.sortOrder,
            "areaId": $.trim($("#audioId").attr("data-id")),
            "tagType": 1,
            "tagId": $.trim($("#tagId").val()),
            "tagName": $.trim($("#tagName").val())
        };
        return temp;
    };
    return oTableInit;
};
// 转写相关
var stt = {
    init: function (isHave) {
        stt.getStt(isHave);
        stt.sttDblclick();
    },
    getStt: function (isHave) {
        $.ajax({
            type: "post",
            url: basePath + "/rest/pending-task-detail/get-stt-info",
            dataType: "json",
            data: {
                serialNumber: $("#serialNumber").html()
            },
            success: function (data) {
                if (data.code == 0) {
                    stt.renderStt(data.data,isHave)
                } else {
                    toastrCog.error(data.msg, 3000)
                }
            }
        })
    },
    renderStt: function (data,isHave) {
        var ul = $('.stt_box');
        ul.html("");
        if (data.length > 0) {
            for (var i = 0; i < data.length; i++) {
                var channel = data[i].channel;//坐席和客户
                var centent = data[i].centent;
                var speed = data[i].speed.toFixed(2);
                var start = data[i].start;
                var end = data[i].end;
                var emotion = data[i].emotion;//情绪
                var imgSrc = "";
                var dur = end - start;
                var perso = channel == 0 ? "坐席" : "客户";
                if (emotion == "0") {
                    imgSrc = "../../../assert/image/anger.png"
                } else {
                    imgSrc = "../../../assert/image/pp.png"
                }
                var $li = $('<li>' +
                    '<div class="stt_name">' + perso + '</div>' +
                    '<i></i>' +
                    '<div class="stt_text">' +
                    '<img src=' + imgSrc + ' alt="">' +
                    '<span>' + centent + '</span>' +
                    '<p class="checked_img hidden"></p>' +
                    '<input type="checkbox" class="checkInput hidden">' +
                    '</div>' +
                    '<div class="timeMsg">' +
                    '<a class="sttTime" href="javascript:;">' + base.formatSeconds(start) + '-' + base.formatSeconds(end) + '</a>' +
                    '<b class="sttSpeed">' + speed + ' 字/秒</b>' +
                    '</div>' +
                    '</li>');
                if (channel == 0) {
                    $li.addClass("stt_left")
                } else {
                    $li.addClass("stt_right")
                }
                $li.attr("data-sTime", start);
                $li.attr("data-eTime", end);
                ul.append($li);
            }
            if(isHave){
                stt.sttHover();
                stt.checkChange();
            }
        }
    },
    checkChange: function () {
        $('.stt_box').on("click", ".checked_img", function () {
            var li = $(this).parents("li");
            var index = li.index();
            var ckeckOn = $(".stt_box li:lt(" + index + ")").find(".checked_img.on");
            var prevIndex = "";
            if (ckeckOn.length > 0) {
                prevIndex = ckeckOn.eq(0).parents("li").index();
            }
            if ($(this).hasClass("on")) {
                $(this).removeClass("on");
                $(this).next().prop("checked", false);
//                    if (ckeckOn.length > 0) {
//                        $(".stt_box li:gt(" + index + ")").find(".checked_img").removeClass("on").addClass("hidden");
//                        $(".stt_box li:gt(" + index + ")").find(".checked_img").next().prop("checked", false);
//                    }
            } else {
                $(this).addClass("on");
                $(this).next().prop("checked", true);
//                    if (ckeckOn.length > 0) {
//                        $(".stt_box li:lt(" + index + "):gt(" + prevIndex + ")").find(".checked_img").addClass("on").removeClass("hidden");
//                        $(".stt_box li:lt(" + index + "):gt(" + prevIndex + ")").find(".checked_img").next().prop("checked", true);
//                    }

            }

        })
    },
    scrollToStt: function (time) {
        time = +(time);
        var container = $(".stt_box");
        var sttPs = $(".stt_box li");
        for (var i = 0; i < sttPs.length; i++) {
            var sttLi = $(sttPs[i]);
            //因为人眼的视觉暂留为0.1-0.4s
            //因此当stt的时长小于0.22s，此处将dur的高亮时间前后各延伸0.1秒
            var off = 0;
            var sTime = Number(sttLi.attr("data-sTime")) - off;
            var eTime = Number(sttLi.attr("data-eTime")) + off;
            //若语音当前时间处于stt的区间段之间，则高亮显示该stt，并将该stt滚动至屏幕视线中
            if (+sTime <= time && +eTime >= time) {
                if (!sttLi.hasClass("on")) {
                    //没有高亮style的stt才进行如下操作，避免重复滚动
                    sttLi.addClass("on");//添加高亮style
                    if (sttLi.offset() && sttLi.offset().top) {
                        //并将该stt滚动至屏幕视线中
                        var scrollTop = sttLi.offset().top - container.offset().top + container.scrollTop() - 35;
                        container.animate({scrollTop: scrollTop}, 5);
                    }
                    break;
                }
            } else {
                //若语音当前时间处于stt的区间段之外，则删除该stt的高亮style
                sttLi.removeClass("on");
            }
        }
    },
    sttDblclick: function () {
        $('.stt_box').unbind().on("dblclick", "li", function (event) {
            $('.stt_box li').removeClass("on");
            var sTime = $(this).attr('data-sTime');
            var eTime = $(this).attr('data-eTime');
            if (sTime!=null && eTime!=null) {
                wave.playRegion(sTime, eTime);
            }
        });
    },
    sttHover: function () {
        $('.stt_box li').hover(function () {
            $(this).find(".checked_img").removeClass("hidden")
        }, function () {
            if (!$(this).find(".checked_img").hasClass("on")) {
                $(this).find(".checked_img").addClass("hidden")
            }
        });
    }
};
var needTagging = {
    init: function() {
        needTagging.orneed();
    },
    //需要标注
    orneed:function(){
        $.ajax({
            type: "post",
            url: basePath + "rest/tagManager/tagAudioUniqueCheck",
            data:{
                serialNumber:$("#serialNumber").text()
            },

            async: false,
            dataType: "json",
            success: function (data) {
                if (data.code == 0) {
                    $(".needTagging").css("background","#337ab7").css("color","#fff").css("cursor","pointer");
                    $(".needTagging").on("click", function () {
                        $("#needtagModal").modal("show");
                    });
                    $("#needtagSave").on("click", function () {
                        needTagging.addTagAudio();
                    });
                } else {
                    $(".needTagging").off("click");
                    $(".needTagging").css("background","rgb(235, 235, 228)").css("color","#666").css("cursor","not-allowed");


                }
            }
        })
    },
    //标注语音添加
    addTagAudio:function(){
        $.ajax({
            type: "post",
            url: basePath + "rest/tagManager/addTagAudio",
            data:{
                serialNumber:$("#serialNumber").text()
            },
            async: false,
            dataType: "json",
            success: function (data) {
                if (data.code == 0) {
                    toastrCog.success(data.msg, 2000);
                    $(".needTagging").css("background","rgb(235, 235, 228)").css("color","#666").css("cursor","not-allowed");
                    needTagging.orneed();
                    $("#needtagModal").modal("hide");
                } else {
                    $(".needTagging").css("background","#337ab7").css("color","#fff").css("cursor","pointer");
                    toastrCog.error(data.msg, 2000);
                }
            }
        })
    }
};
needTagging.init();